package com.lly.bigdata.bgayx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lly.bigdata.bgayx.common.utils.IdUtils;
import com.lly.bigdata.bgayx.entity.SysOrg;
import com.lly.bigdata.bgayx.entity.SysUser;
import com.lly.bigdata.bgayx.mapper.SysOrgMapper;
import com.lly.bigdata.bgayx.service.ISysOrgService;
import com.lly.bigdata.bgayx.vo.Result;
import com.lly.bigdata.bgayx.vo.SearchModel;
import com.lly.bigdata.bgayx.vo.ZTreeBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author lly
 * @since 2020-10-21
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {

    @Override
    public Result queryOrgTree(SearchModel searchModel) {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper();
        LambdaQueryWrapper<SysOrg> lambda = queryWrapper.lambda();
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getS_name())) {
            lambda.like(SysOrg::getOrgName, searchModel.getS_name());
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(searchModel.getNodeid())) {
            lambda.eq(SysOrg::getPid, searchModel.getNodeid());
        }
        queryWrapper.orderByAsc("org_sort");
        List<SysOrg> list = baseMapper.selectList(queryWrapper);
        return Result.pageOk(list);
    }

    /**
     * @return java.util.List<ZTreeBean>
     * @Author lly
     * @Description 组织结构树
     * @Date 2021/8/3 15:45
     * @Param []
     **/
    @Override
    public List<ZTreeBean> getOrgTree() {
        List<SysOrg> sysOrgs = baseMapper.selectList(null);
        List<ZTreeBean> treeBeans = initTree(sysOrgs);
        return treeBeans;
    }

    @Override
    @Transactional(readOnly = false)
    public Result addOrUpdateOrg(SysOrg sysOrg, SysUser sysUser) {
        if (StringUtils.isEmpty(sysOrg.getId())) {
            sysOrg.setId(IdUtils.simpleUUID());
            sysOrg.setCreateTime(LocalDateTime.now());
            sysOrg.setCreateBy(sysUser.getUsername());
            if ("0".equals(sysOrg.getPid())) {
                sysOrg.setTreeLevel(1);
            } else {
                SysOrg porg = this.getById(sysOrg.getPid());
                sysOrg.setTreeLevel(porg.getTreeLevel() + 1);
                porg.setTreeLeaf("0");//不是子节点
                this.updateById(porg);
            }
            sysOrg.setTreeLeaf("1");//是子节点
            this.save(sysOrg);
        } else {
            SysOrg org = this.getById(sysOrg.getId());
            SysOrg porg = this.getById(sysOrg.getPid());
            if (porg != null) {
                porg.setTreeLeaf("0");
                this.updateById(porg);
                sysOrg.setTreeLevel(porg.getTreeLevel() + 1);
            }
            sysOrg.setTreeLeaf(org.getTreeLeaf());
            sysOrg.setTreeLevel(org.getTreeLevel());
            sysOrg.setStatus(org.getStatus());
            sysOrg.setCreateBy(org.getCreateBy());
            sysOrg.setCreateTime(org.getCreateTime());
            this.updateById(sysOrg);
            if (org != null && !org.getPid().equals(sysOrg.getPid())) {
                Page page = queryPid(org.getPid(), 1, 1);
                if (page.getRecords().size() == 0) {//原来上级是不是就没有了
                    SysOrg byId1 = this.getById(org.getPid());//
                    byId1.setTreeLeaf("1");
                    this.updateById(byId1);
                }
            }
        }
        return Result.ok();
    }

    @Override
    @Transactional
    public Result delOrg(String id) {
        Page page = queryPid(id, 1, 1);
        if (page.getTotal() > 0) {
            return Result.fail("无法删除，请删除所有子节点");
        }
        SysOrg byId = this.getById(id);
        this.removeById(id);
        Page page1 = queryPid(byId.getPid(), 1, 1);
        if (page1.getRecords().size() == 0) {
            SysOrg byId1 = this.getById(byId.getPid());//
            byId1.setTreeLeaf("1");
            this.updateById(byId1);
        }
        return Result.ok();
    }

    public Page queryPid(String pid, Integer curr, Integer rows) {
        Page page = new Page(curr, rows);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("pid", pid);
        Page page1 = this.page(page, queryWrapper);//还有没有同级
        return page1;
    }

    /**
     * @return java.util.List<ZTreeBean>
     * @Author lly
     * @Description 初始化树
     * @Date 2021/8/3 15:37
     * @Param [sysOrgs]
     **/
    private List<ZTreeBean> initTree(List<SysOrg> sysOrgs) {
        List<ZTreeBean> treeBeans = new ArrayList<>();
        for (SysOrg sysOrg : sysOrgs) {
            if (StringUtils.isBlank(sysOrg.getPid()) || "0".equals(sysOrg.getPid())) {
                ZTreeBean treeBean = new ZTreeBean();
                treeBean.setId(sysOrg.getId());
                treeBean.setName(sysOrg.getOrgName());
                treeBean.setPid(sysOrg.getPid());
                treeBean.setOpen(true);
                dgTree(treeBean, sysOrgs);
                treeBeans.add(treeBean);
            }
        }
        return treeBeans;
    }

    private void dgTree(ZTreeBean zTreeBean, List<SysOrg> sysOrgs) {
        // List<ZTreeBean> treeBeans=new ArrayList<>();
        for (SysOrg sysOrg : sysOrgs) {
            if (StringUtils.isNotBlank(sysOrg.getPid()) && sysOrg.getPid().equals(zTreeBean.getId())) {
                ZTreeBean zTreeBean1 = new ZTreeBean();
                zTreeBean1.setName(sysOrg.getOrgName());
                zTreeBean1.setId(sysOrg.getId());
                zTreeBean1.setPid(sysOrg.getPid());
                zTreeBean1.setOpen(true);
                dgTree(zTreeBean1, sysOrgs);
                // treeBeans.add(zTreeBean1);
                if (zTreeBean.getChildren() == null) {
                    zTreeBean.setChildren(new ArrayList<>());
                }
                zTreeBean.getChildren().add(zTreeBean1);
                zTreeBean.setIsParent(true);
            }
        }
    }


}
